package com.luoran.bartalks.api;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.annotation.OperationLog;
import com.luoran.bartalks.core.AppUser;
import com.luoran.bartalks.entity.biz.BtPackingListMateriel;
import com.luoran.bartalks.entity.biz.BtPlanBizPic;
import com.luoran.bartalks.service.IBtPackingListMaterielService;
import com.luoran.bartalks.service.IBtPlanBizPicService;
import com.luoran.bartalks.service.IBtPlanBizService;
import com.luoran.bartalks.utils.EnumOperationType;
import com.luoran.bartalks.utils.UUID;

@RestController
@RequestMapping("/api/forcedPhoto")
public class ForcedPhotoApi {

	@Autowired
	private IBtPlanBizPicService planBizPicService;

	@Autowired
	private IBtPackingListMaterielService packingListMaterielService;

	@Autowired
	private IBtPlanBizService planBizService;

	@Value("${image.path}")
	private String imagePath;

	@Value("${image.url}")
	private String imageUrl;

	private static final Logger log = LoggerFactory.getLogger(ForcedPhotoApi.class);

	@RequestMapping("/savePhoto")
	@OperationLog(EnumOperationType.PHOTOGRAPH)
	public String savePhoto(HttpServletRequest req) {
		log.info("强制拍照保存照片");
		JSONObject res = new JSONObject();
		String qrcodeStr;
		String planPositionId;
		int bizType;
		try {
			qrcodeStr = req.getParameter("qrcode");
			planPositionId = req.getParameter("planPositionId");
			String bizTypestr = req.getParameter("bizType");
			bizType = Integer.parseInt(bizTypestr);
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
			res.put("state", false);
			res.put("msg", "参数出错,请重新登录后再试");
			return res.toJSONString();
		}
		// qrcode校验
		if (StringUtils.isEmpty(qrcodeStr)) {
			res.put("state", false);
			res.put("msg", "服务器出错,请重新登录后再试");
			return res.toJSONString();
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
		Iterator<String> fileNames = multipartRequest.getFileNames();
		if (!fileNames.hasNext()) {
			res.put("state", false);
			res.put("msg", "请先拍照再上传");
			return res.toJSONString();
		}
		MultipartFile file = multipartRequest.getFile(fileNames.next());// 获取文件 流对象
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).toLowerCase();// 获取后缀
		String newName = UUID.get() + suffix;// 新名字
		String deposition = imagePath + "/" + newName;
		String picUrl = imageUrl + "/" + newName;
		try {
			File targetFile = new File(imagePath);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			FileOutputStream fos = new FileOutputStream(new File(deposition));
			fos.write(file.getBytes());
			fos.flush();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
			res.put("state", false);
			res.put("msg", "系统异常");
			return res.toJSONString();
		}
		// 通过箱单物料ID可确保物料在计划中的唯一,也就是biz装卸货操作表的装货/卸货数据的唯一性
		BtPackingListMateriel packingListMateriel = packingListMaterielService
				.getItemByMaterielQrcodeAndCompanyId(qrcodeStr, AppUser.get().getCompanyId());
		String packingListMaterielId = packingListMateriel.getId();
		String planBizId = planBizService.getIdByPackingListMaterielId(packingListMaterielId, planPositionId, bizType);
		// 保存记录
		BtPlanBizPic planBizPic = new BtPlanBizPic();
		planBizPic.setForcedPicUrl(picUrl);
		planBizPic.setPlanBizId(planBizId);
		planBizPicService.addPlanBizPic(planBizPic);
		res.put("state", true);
		res.put("msg", "图片上传成功");
		return res.toJSONString();
	}
}
